package com.ljj.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljj.commonutils.R;
import com.ljj.eduservice.client.VodClient;
import com.ljj.eduservice.entity.EduVideo;
import com.ljj.eduservice.mapper.EduVideoMapper;
import com.ljj.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljj.servicebase.handler.MicroCloudException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-09-11
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    private VodClient vodClient;
    @Override
    public void removeVideoByCourseId(String courseId) {
        //根据课程ID查询所有视频ID
        QueryWrapper wrapperVideo = new QueryWrapper();
        wrapperVideo.eq("course_id",courseId);
        wrapperVideo.select("video_source_id");
        List<EduVideo> videos = baseMapper.selectList(wrapperVideo);
        List<String> ids = new ArrayList<>();
        for(EduVideo video: videos){
            String sourceId = video.getVideoSourceId();
            if( sourceId!=null && !"".equals(sourceId) )
                ids.add(video.getVideoSourceId());
        }

        //先删数据
        QueryWrapper<EduVideo> wrapper = new QueryWrapper();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);

        //再删视频
        if(ids.size()>0){
            //获取远程调用结果
            R result = vodClient.deleteVideos(ids);
            if(result.getCode()==20001){
                //远程调用失败，抛出异常
                throw new MicroCloudException(result.getCode(),result.getMessage());
            }
        }
    }

    @Override
    public void removeVideoById(String id) {
        //根据小节ID 获取 视频ID
        EduVideo video = baseMapper.selectById(id);
        String videoSourceId=null;
        if(video!=null)
            videoSourceId = video.getVideoSourceId();

        //先删数据
        baseMapper.deleteById(id);

        //再删视频
        if( videoSourceId!=null && !"".equals(videoSourceId)){
            R result = vodClient.deleteVideo(videoSourceId);
            System.out.println(result);
            if(result.getCode()==20001){
                throw new MicroCloudException(result.getCode(),result.getMessage());
            }
        }
    }
}
